# -*- coding:utf-8 -*-
from flask import session, render_template
from flask_wtf import FlaskForm
from sqlalchemy import or_, and_
from wtforms import StringField, PasswordField, DateField, RadioField
from wtforms.fields.html5 import EmailField
from wtforms.validators import DataRequired, EqualTo, Email, Length
from wtforms.widgets import TextInput, PasswordInput
from flask_mail import Message
from apps.ext import db
from apps.models import User


class RegisterForm(FlaskForm):
    username = StringField(
        label='用户名',
        validators=[
            DataRequired(message='用户名不能为空'),
            Length(6, 18, message="用户名需大于6个字符小于18个字符")
        ],
        widget=TextInput(),
        render_kw={'class': 'form-control'},
    )

    password = PasswordField(
        label='密码',
        validators=[
            DataRequired(message='密码不能为空'),
            Length(6, 18, message="密码需大于6个字符小于18个字符")
        ],
        widget=PasswordInput(),
        render_kw={'class': 'form-control'}
    )

    enter_password = PasswordField(
        label='重复密码',
        validators=[
            DataRequired(message='重复密码不能为空'),
            EqualTo('password', message="两次密码输入不一致")
        ],
        widget=PasswordInput(),
        render_kw={'class': 'form-control'}
    )

    email = EmailField(
        label='邮箱',
        validators=[
            DataRequired(message='邮箱不能为空'),
            Email(message='邮箱格式错误')
        ],
        widget=TextInput(input_type='email'),
        render_kw={'class': 'form-control'}
    )

    def is_register(self):
        username = self.username.data
        email = self.email.data
        user = User.query.filter(or_(User.username == username, User.email == email)).first()
        if user:
            return "用户名或邮箱已注册"
        else:
            return False

    def create_user(self, img_url):
        user = User()
        user.username = self.username.data
        user.password = self.password.data
        user.email = self.email.data
        user.head_img = img_url
        db.session.add(user)
        db.session.commit()
        session["username"] = self.username.data
        return user

    def send_email(self):
        from apps import send_async_email
        message = Message("欢迎注册", recipients=[self.email.data])
        message.html = render_template("account/register/user_active.html", username=self.username.data,
                                       active_url='http://127.0.0.1:9000/account/verify/')
        send_async_email.delay(message)


class LoginForm(FlaskForm):
    username = StringField(
        label='用户名',
        validators=[
            DataRequired(message='用户名不能为空'),
        ],
        widget=TextInput(),
        render_kw={'class': 'form-control'},
    )

    password = PasswordField(
        label='密码',
        validators=[
            DataRequired(message='密码不能为空'),
        ],
        widget=PasswordInput(),
        render_kw={'class': 'form-control'}
    )

    def can_login(self):
        username = self.username.data
        password = self.password.data
        user = User.query.filter(and_(User.username == username, User.password == password)).first()
        if user:
            user.is_login = 1
            db.session.commit()
            session_dict = {'is_login': True, 'user_id': user.user_id, 'username': username, 'img': user.head_img}
            session["user"] = session_dict
            return True
        else:
            return False


class UserUpdateForm(FlaskForm):
    username = StringField(
        label='用户名',
        validators=[
            DataRequired(message='用户名不能为空'),
            Length(6, 18, message="用户名需大于6个字符小于18个字符")
        ],
        widget=TextInput(),
        render_kw={'class': 'form-username'},
    )

    sex = RadioField(
        label='性别',
        choices=(
            (0, '隐藏'),
            (1, '男'),
            (2, '女'),
        ),
        coerce=int,
        render_kw={'class': 'form-sex'}
    )

    birthday = DateField(
        label='生日',
        validators=[DataRequired()],
        format='%Y-%m-%d',
        render_kw={'class': 'form-birthday'}
    )

    email = EmailField(
        label='邮箱',
        validators=[
            DataRequired(message='邮箱不能为空'),
            Email(message='邮箱格式错误')
        ],
        widget=TextInput(input_type='email'),
        render_kw={'class': 'form-email'}
    )

    def update_user(self, user, img_url=None):
        user.username = self.username.data
        user.birthday = self.birthday.data
        user.sex = self.sex.data
        user.email = self.email.data
        # 判断用户是否重新上传头像
        if img_url:
            user.head_img = img_url
            db.session.commit()
        else:
            db.session.commit()


class UpdatePasswordForm(FlaskForm):
    old_password = PasswordField(
        label='原密码',
        validators=[
            DataRequired(message='密码不能为空'),
        ],
        widget=PasswordInput(),
        render_kw={'class': 'form-control'}
    )
    new_password = PasswordField(
        label='新密码',
        validators=[
            DataRequired(message='密码不能为空'),
            Length(6, 18, message="密码需大于6个字符小于18个字符")
        ],
        widget=PasswordInput(),
        render_kw={'class': 'form-control'}
    )
    enter_password = PasswordField(
        label='确认密码',
        validators=[
            DataRequired(message='密码不能为空'),
            EqualTo('new_password', message="两次密码输入不一致")
        ],
        widget=PasswordInput(),
        render_kw={'class': 'form-control'}
    )

    def update_password(self, user):
        user.password = self.new_password.data
        db.session.commit()
